<?php
// 应用公共文件


use app\model\UserModel;
use GuzzleHttp\Client;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

function verification_username($string)
{
    return preg_match('/^[A-Za-z0-9_]{6,32}$/', $string);
}


/*
 * 验证用户名的函数
 * 用户名需要满足英文字符串数_并且字符不得大在6-32位
 * */
function verification_password($string)
{
    return preg_match('/^[a-zA-Z\d_]{6,32}$/', $string);
}


/*
 * 验证手机号的函数
 * 用户名需要满足英文字符串数_并且字符不得大在6-32位
 * */
function verification_mobile($string)
{
    return preg_match('/^1[345789]\d{9}$/', $string);
}



/*
 * 检验邮编
 * */
function verification_postcode($string)
{
    return preg_match("/^1[0-9]{5}$|^2[0-9]{5}$|^3[0-9]{5}$/", $string);
}


/*
 * 验证邮箱的函数
 * 用户名需要满足英文字符串数_并且字符不得大在6-32位
 * */
function verification_email($string)
{
    return preg_match('/^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@([a-zA-Z0-9]+[-.])+([a-z]{2,5})$/', $string);
}


/*
 * 验证QQ的函数
 * 用户名需要满足英文字符串数_并且字符不得大在6-32位
 * */
function verification_qq($string)
{
    return preg_match('/^\d{5,12}$/i', $string);
}

/*
 * 验证微信的函数
 * 用户名需要满足英文字符串数_并且字符不得大在6-32位
 * */
function verification_wx($string)
{
    return preg_match('/^[_a-zA-Z0-9]{5,19}+$/i', $string);
}


/*
 * 验证身份证的函数
 * 用户名需要满足英文字符串数_并且字符不得大在6-32位
 * */
function verification_id_card($string)
{
    return preg_match('/\d{14}(\d{4}|(\d{3}[xX])|\d{1})/', $string);
}


/*
 * 验证银行卡的函数
 * 用户名需要满足英文字符串数_并且字符不得大在6-32位
 * */
function verification_bank_card($string)
{
    return preg_match('/^(\d{15}|\d{16}|\d{19})$/i', $string);
}

function verification_date($dateString)
{
    $dateObj = DateTime::createFromFormat('Y-m-d', $dateString);

    if ($dateObj && $dateObj->format('Y-m-d') === $dateString) {
        return true;
    } else {
        return false;
    }
}
/*
   *
   * 生成验证码
   * */
function  generateRandomNumber($length) {
    $randomNumber = '';
    for ($i = 0; $i < $length; $i++) {
        $randomNumber .= mt_rand(0, 9); // 生成随机数字
    }
    return $randomNumber;
}

function generateRandomCode($length = 8) {
    $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $index = rand(0, strlen($characters) - 1);
        $randomString .= $characters[$index];
    }
    return $randomString;
}


/*
 *
 * 发送消息
 * */

function sendSms($mobile,$msg)
{
    return true;
}

function addWxPayLog($filename,$content,$writeTime=true){

    $logFile =  app()->getRootPath() . 'public'.DIRECTORY_SEPARATOR.'wxpay'.DIRECTORY_SEPARATOR.date('Ymd').'_'.$filename;
    if($writeTime){
        return error_log(date('Y-m-d H:i:s') . ',' .print_r($content,1) ."\r\n",3,$logFile);
    }else{
        return   error_log($content."\r\n",3,$logFile);
    }
}

function addLog($filename,$content,$writeTime=true){

    $logFile =  app()->getRootPath() . 'public'.DIRECTORY_SEPARATOR.'log'.DIRECTORY_SEPARATOR.date('Ymd').'_'.$filename;
    if($writeTime){
        return error_log(date('Y-m-d H:i:s') . ',' .print_r($content,1) ."\r\n",3,$logFile);
    }else{
        return   error_log($content."\r\n",3,$logFile);
    }
}


function generateOrderId()
{
    // 移除时间戳中的空格和小数点，只保留数字部分
    $microtime = str_replace([' ', '.'], '', microtime(true));

    // 获取随机数，确保即使在同一微秒内，也可以生成不同的订单号
    $rand = mt_rand(10000000, 99999999);

    // 组合订单号
    $orderNumber = $microtime . $rand;

    return $orderNumber;
}

function tranTime($time) {
    $rtime = date("m-d H:i",$time);
    //$htime = date("H:i",$time);
    $htime='';
    $time = time() - $time;

    if ($time < 60) {
        $str = '刚刚';
    }
    elseif ($time < 60 * 60) {
        $min = floor($time/60);
        $str = $min.'分钟前';
    }
    elseif ($time < 60 * 60 * 24) {
        $h = floor($time/(60*60));
        $str = $h.'小时前 '.$htime;
    }
    elseif ($time < 60 * 60 * 24 * 3) {
        $d = floor($time/(60*60*24));
        if($d==1)
            $str = '昨天 '.$rtime;
        else
            $str = '前天 '.$rtime;
    }
    else {
        $str = substr($time,0,10);
    }
    return $str;
}

/*
 * 检测是不是联合订单号
 * */
function isUnionOrderId($orderId){
    return substr($orderId,0,1) == "L" ? true : false;
}


/*
 * 获取微信的accessToken
 * */
function getAccessToken(){
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
    $appid = config('wx.appid');
    $secret = config('wx.secret');
    $url .= "&appid={$appid}&secret={$secret}";
    $response = file_get_contents($url);
    $result = json_decode($response, true);
    return  $result['access_token'];
}
/*
 * 获取物流公司列表
 * */
function getExpressList(){
    $url = "https://api.weixin.qq.com/cgi-bin/express/business/delivery/getall?access_token=".getAccessToken();
    $client = new Client([ 'verify' => false]);
    $response =$client->request('GET', $url);
    return $response;
}

/*
 * 获取物流轨迹
 * */
function getLogistics($openid,$waybill_id,$delivery_id){
    if(empty($openid) || empty($waybill_id) || empty($delivery_id)) return false;
    $url = "https://api.weixin.qq.com/cgi-bin/express/business/path/get?access_token=".getAccessToken();
    $client = new Client([ 'verify' => false]);
    $response =$client->post($url,[
        'json' => [
            "openid"=> $openid ,
            "delivery_id"=>  $delivery_id,
            "waybill_id"=>  $waybill_id
        ]
    ]);
    return $response;
}


/*
 * 获取物流公司列表
 * */
function bindExpressAccount($type,$delivery_id,$biz_id, $password, $remark_content=''){
    $url = "https://api.weixin.qq.com/cgi-bin/express/business/account/bind?access_token=".getAccessToken();
    $client = new Client([ 'verify' => false]);
    $response =$client->post($url,[
        'json' => [
            "type"=> $type ,
            "delivery_id"=>  $delivery_id,
            "biz_id"=>  $biz_id,
            "password"=>  $password,
            "remark_content"=>  $remark_content,
        ]
    ]);
    return $response;
}


/*
 * 获取所有绑定的快递账号
 * */
function getAllExpressAccount(){
    $url = "https://api.weixin.qq.com/cgi-bin/express/business/account/getall?access_token=".getAccessToken();
    $client = new Client([ 'verify' => false]);
    $response =$client->request('GET', $url);
    return $response;
}

/*
 * 获取电子面单余额
 * */
function getExpressAccountQuota($delivery_id,$biz_id){
    $url = "https://api.weixin.qq.com/cgi-bin/express/business/quota/get?access_token=".getAccessToken();
    $client = new Client(['verify' => false]);
    $response =$client->post($url,[
        'json' => [
            "delivery_id"=>  $delivery_id,
            "biz_id"=>  $biz_id,
        ]
    ]);
    return $response;
}


/*
 * 在线下单接口
 * */
function createExpressOrder($data){
    $url = "https://api.weixin.qq.com/cgi-bin/express/business/order/add?access_token=".getAccessToken();
    $client = new Client(['verify' => false]);
    $response =$client->post($url,[
        'body' => json_encode($data, JSON_UNESCAPED_UNICODE),  // 自定义 JSON 编码
        'headers' => [
            'Content-Type' => 'application/json; charset=utf-8'
        ],
    ]);
    return $response;
}


function cancelExpressOrder($data){
    $url = "https://api.weixin.qq.com/cgi-bin/express/business/order/cancel?access_token=".getAccessToken();
    $client = new Client(['verify' => false]);
    $response =$client->post($url,[
        'body' => json_encode($data, JSON_UNESCAPED_UNICODE),  // 自定义 JSON 编码
        'headers' => [
            'Content-Type' => 'application/json; charset=utf-8'
        ],
    ]);
    return $response;
}


function sendGoodsForLuDan($data){
    $url = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=".getAccessToken();
    $client = new Client(['verify' => false]);
    $response =$client->post($url,[
        'body' => json_encode($data, JSON_UNESCAPED_UNICODE),  // 自定义 JSON 编码
        'headers' => [
            'Content-Type' => 'application/json; charset=utf-8'
        ],
    ]);
    return $response;
}




/*
 * 模拟更新物流轨迹
 * */
function testUpdateLogistics($data){
    $url = "https://api.weixin.qq.com/cgi-bin/express/business/test_update_order?access_token=".getAccessToken();
    $client = new Client(['verify' => false]);

    $response =$client->post($url, [
        'body' => json_encode($data, JSON_UNESCAPED_UNICODE),  // 自定义 JSON 编码
        'headers' => [
            'Content-Type' => 'application/json; charset=utf-8'
        ],
    ]);
    return $response;
}


function array_contains_array($array1, $array2) {
    // 比较 $array2 是否是 $array1 的子集
    return count(array_diff_assoc($array2, $array1)) === 0;
}


function exportToExcel(array $headers, array $dataList, string $fileName = 'export.xlsx', string $sheetName = 'Sheet1')
{
    // 创建 Spreadsheet 实例
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();

    // 设置表头
    if (!empty($headers)) {
        foreach ($headers as $colIndex => $header) {
            $column = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($colIndex + 1);
            $sheet->setCellValue($column . '1', $header);
        }
    }

    // 填充数据
    $rowIndex = 2; // 数据从第2行开始
    foreach ($dataList as $rowData) {
        foreach ($rowData as $colIndex => $cellValue) {
            $column = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($colIndex + 1);
            $sheet->setCellValue($column . $rowIndex, $cellValue);
        }
        $rowIndex++;
    }

    // 设置工作表名称
    $spreadsheet->getActiveSheet()->setTitle($sheetName);

    // 设置文档属性（可选）
    $spreadsheet->getProperties()
        ->setCreator("Your System")
        ->setLastModifiedBy("Your System")
        ->setTitle("Exported Data")
        ->setSubject("Exported Data from PHP")
        ->setDescription("Generated by PhpOffice\PhpSpreadsheet");

    // 输出到浏览器，强制下载
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="' . $fileName . '"');
    header('Cache-Control: max-age=0');

    $writer = new Xlsx($spreadsheet);
    $writer->save('php://output');
    exit;
}



/*
* 检查是否登录
* */
function getUid(){
    $token = request()->header('token');
    if(empty($token)){
        return null;
    }
    $userInfo =  (new UserModel())->getUserCacheByOpenId($token);

    if(empty($userInfo) || empty($userInfo["uid"])){
        return null;
    }

    return $userInfo["uid"];
}
